package com.murongxue.blog.servlet;

import com.murongxue.blog.dao.UserDao;
import com.murongxue.blog.model.User;
import com.murongxue.blog.service.UserService;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/do-register")
public class DoRegisterServlet extends HttpServlet {
    private final UserService userService = new UserService();

    // 按需写代码 -> 自顶向下设计
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 读取用户提交的信息
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");
        String avatar = req.getParameter("avatar");
        String git = req.getParameter("git");

        User user = userService.register(username, nickname, password, avatar, git);
        // 3. 至少区分出 3 种情况
        // 1) 注册成功                      user != null
        // 2) 由于用户名重复导致的注册失败      user == null
        // 3) 由于系统操作导致的注册失败       以异常方式体现

        // 异常直接交给 Tomcat 去处理，Tomcat 自动生成 500 页面【虽然对用户不友好，但实现简单】
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        if (user != null) {
            // 放置 session，视为用户登录了
            HttpSession session = req.getSession();
            session.setAttribute("currentUser", user);
            // 这里也可以用模板去完成
            writer.printf("<p>注册成功，点击<a href='/'>此处</a>跳转到首页</p>\r\n");
        } else {
            // 这里也可以用模板去完成
            writer.printf("<p>注册失败，用户名已被使用，点击<a href='/register.html'>此处</a>重新注册</p>\r\n");
        }
    }
}
